/**
 * SPDX-FileCopyrightText: 2023-2025 Sangfor Technologies Inc.
 * SPDX-License-Identifier: Mulan PSL v2
 */
<template>
    <div ref="kafkaBox"
         class="content-wrapper algorithm-manager__container">
        <div class="switch-card-container">
            <div class="switch-card-container__content">
                <page-title :title-name="algorithmTitle" />
                <div class="algorithm-market__wrap">

                    <div class="market-nav__left">
                        <div class="market-nav__title">
                            <lang>分类</lang>
                        </div>
                        <div class="market-nav__total">
                            <div class="market-nav__list">
                                <div
                                    v-for="(item, index) in aihubTypeList"
                                    :key="index"
                                    :class="{'active':item.value===scope}"
                                    class="market-nav__item"
                                    @click="changeAihubTypeList(item)">
                                    <i class="icon iconfont  m-r5" :class="item.icon"></i>
                                    {{ item.name }}
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="card-container">
                        <sf-grid>
                            <sf-toolbar ref="toolbar">
                                <sf-button
                                    ref="submit"
                                    class="creat-button btn-blank"
                                    icon-cls="iconxinzeng2"
                                    @click="_addAIHub">
                                    <lang>本地上传</lang>
                                </sf-button>
                                <sf-searchfield
                                    v-model="searchParams.keyword"
                                    class="pull-right"
                                    placeholder="请输入关键字"
                                    @trigger="_startSearch"
                                    @clear="_startSearch" />
                            </sf-toolbar>
                        </sf-grid>

                        <div v-if="algorithmList.length"
                                class="algorithm-list__total">
                            <div
                                v-for="(item,index) in algorithmList"
                                :key="index"
                                class="algorithm-list__item">
                                <div class="algorithm-item__top">
                                    <div class="left">
                                        <div class="algorithm-title">
                                            【算法】{{ item.name }}
                                        </div>
                                        <div class="m-r15 font-important">{{item.userId}}</div>
                                        <div class="algorithm-time">
                                            <div class="algorithm-time__text font-important">
                                                {{ encodeTime(item.updateTime) }}
                                            </div>
                                        </div>
                                       <div class="m-l20 font-important">下载次数 <span class="blue">{{item.times}}</span></div>
                                    </div>
                                    <div class="right">
                                        <sf-button
                                            class="m-r15"
                                            icon-cls="icondownload"
                                            size="normalless"
                                             @click="_downloadFile(item)">
                                            <lang>下载</lang>
                                        </sf-button>
                                        <!-- 用户只能编辑删除自己的 -->
                                        <sf-button
                                            v-if="item.userId === userID"
                                            class="m-r15"
                                            icon-cls="iconsip-edit"
                                            size="normalless"
                                            @click="_editAIHub(item)">
                                            <lang>编辑</lang>
                                        </sf-button>
                                        <sf-button
                                            v-if="item.userId === userID"
                                            class="m-r15"
                                            icon-cls="icon-comp-delete"
                                             size="normalless"
                                            @click="_deleteAlgorithm(item)">
                                            <lang>删除</lang>
                                        </sf-button>
                                    </div>
                                </div>
                                <div  class="algorithm-item__center">
                                    <div v-if="item.tags" class="flex">
                                        <div v-for="(i,index) in item.tags.split(',')" :key="index" class="tag-demo m-r10">
                                            <sf-tag type="primary"
                                                    effect="light"
                                                    isOval
                                                    >
                                                {{ i }}
                                            </sf-tag>
                                        </div>
                                    </div>
                                </div>
                                <div class="algorithm-item__bottom">
                                    <lang>描述：</lang>
                                    <div class="font-important description sfv-ellipsis"
                                            :title="item.description">
                                        {{ item.description || '-' }}
                                    </div>
                                </div>
                            </div>
                        </div>
                        <sf-paging-bar v-if="algorithmList.length"
                                        :options="pageOptions"
                                        :layout="['pager']"
                                        @pagechange="_onPageChange" />
                        <empty-panel
                            v-else
                            :title="_('暂时没有AI集市列表')" />
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import { encodeDate } from 'src/util/format';
import pageTitle from '../common/page_title/page_title.vue';
import EmptyPanel from 'src/components/empty_panel.vue';
const PAGE_COUNT = 5;
import trainingUrlAdapter from 'src/home/mod_common/training_url_adapter';
import store from 'src/vuex/store';
let userID = store.state.userId;

const AIHUB_URL = {
    get: trainingUrlAdapter(`user/${userID}/aiHub/file`),
    delete: trainingUrlAdapter(`user/${userID}/aiHub/file`),
    post: trainingUrlAdapter(`user/${userID}/aiHub/file`),
    put: trainingUrlAdapter(`aiHub/file`),
    download:trainingUrlAdapter(`aiHub/file`),
};

import addAlgorithmForm from './label_form/add_algorithm.vue';
import { downloadFile } from 'src/util/blob_download';


export default {
    components:{
        pageTitle,
        EmptyPanel
    },

    data () {
        return {
            pageOptions: {
                pageSize: PAGE_COUNT,
                activePage : 1,
                total:0
            },
            algorithmList: [],
            algorithmTitle: _('AI集市'),
            pageTotal:  0,
            groupList: [],
            cardProps: {},
            searchParams: {
                pageSize: PAGE_COUNT,
                pageNum: 0,
                scope: '',
                keyword:''
            },
            aihubTypeList:[{
                name:_('All'),
                value:'ALL',
                icon:'iconsip-lefttree-manager'
            },{
                name:_('牛人分享'),
                value:'OTHERS',
                icon:'iconzhanghaoguanliyuan'
            },{
                name:_('我的分享'),
                value:'',
                icon:'iconyonghu'
            }],
            scope:'ALL'
        }
    },
    computed:{
        userID(){
            return userID;
        }
    },

    mounted () {
        this.refreshGrid();
    },

    methods: {
        changeAihubTypeList(item){
            this.scope = item.value;
            this.refreshGrid();
        },
        // 刷新grid
        async refreshGrid () {
            this.searchParams.scope = this.scope;
            let jsonData = await this.$ajax.get(AIHUB_URL.get, this.searchParams);
            this.$unmask();
            let {success, msg, data} = jsonData;
            if (!success) {
                this.$showErr(msg || _('加载数据失败'));
                return;
            }
            this.algorithmList = data.list;
            this.pageOptions.total = data.total;
        },


        // 新增算法类型弹窗
        _createAlgorithmFormWin () {
            if (!this.algorithmFormWin) {
                this.algorithmFormWin = this.$modal(addAlgorithmForm, {
                    autoDestory: true
                });
            }
            return this.algorithmFormWin;
        },

        // 新增算法模板
        _addAIHub () {
            let formWin = this._createAlgorithmFormWin();
            let vm = this;
            formWin.open({
                reset: true,
                title: _('新增算法'),
                data:{
                    algorithmTypeId:this.searchParams.algorithmTypeId
                },
                submit: () => {
                    let ajaxParams = formWin.formRoot.getJsonValue();
                    if (!ajaxParams.file) {
                        return this.$showErr(_('请上传算法文件'));
                    };
                    if (ajaxParams.fileMd5) {
                        this.ajaxSubmitAlgorithm(ajaxParams,formWin);
                    };
                },
                uploadSuccessCallback (jsonData) {
                    let {success, msg} = jsonData;
                    if (!success) {
                        return vm.$showErr(msg || _('上传失败'));
                    }
                    vm.$ok(msg || _('上传成功'));
                    formWin.hide();
                    vm.refreshGrid();
                },
                uploadFailureCallback (jsonData) {
                    vm.$showErr(jsonData.msg || _('上传算法失败'));
                    formWin.hide();
                }
            });
        },

        // 编辑算法模板
        _editAIHub (record) {
            let formWin = this._createAlgorithmFormWin();
            formWin.formRoot.setJsonValue(record);
            formWin.open({
                title: _('编辑算法'),
                data:{
                    isEdit:true
                },
                submit: () => {
                    let ajaxParams = formWin.formRoot.getJsonValue();
                    this.ajaxEditAIHub(ajaxParams, formWin);
                }
            });
        },
        // 执行删除操作
        async ajaxEditAIHub (params, formWin) {
            this.$mask();
            let jsonData = await this.$ajax.put(`${AIHUB_URL.put}/${params.id}`,params);
            this.$unmask();
            let {success, msg} = jsonData;
            if (!success) {
                return this.$showErr(msg || _('编辑失败'));
            }
            formWin.hide();
            this.$ok(_('编辑成功'));
            this.refreshGrid();
        },
        // 表格单项删除
        _deleteAlgorithm (item) {
            let params = {
                id:item.id
            };
            this.$confirm({
                title: _('提示'),
                subTitle: _('确定要删除{0}算法吗？', item.name),
                icon: 'warning',
                autoClose: true,
                callback: actionName => {
                    if (actionName === 'submit') {
                        this.ajaxDeleteTableItem(params);
                    }
                }
            });
        },

        // 新增/编辑算法模板
        async ajaxSubmitAlgorithm (params, formWin) {
            formWin.formRoot.beginUpload();
        },

        // 执行删除操作
        async ajaxDeleteTableItem (params) {
            this.$mask();
            let jsonData = await this.$ajax.delete(`${AIHUB_URL.delete}/${params.id}`);
            this.$unmask();
            let {success, msg} = jsonData;
            if (!success) {
                return this.$showErr(msg || _('编辑失败'));
            }
            this.$ok(_('删除成功'));
            this.refreshGrid();
        },

        _refreshManagers () {
            this.refreshGrid();
        },

        _startSearch () {
            this.refreshGrid();
        },

        _onPageChange (pageNum) {
            Object.assign(this.searchParams, {
                pageNum: pageNum - 1
            });
            this.refreshGrid();
        },

        _onSizeChange (nowPageIndex, nowPageSize) {
            Object.assign(this.searchParams, {
                pageNum: nowPageIndex - 1,
                pageSize: nowPageSize
            });
            this.refreshGrid();
        },

        encodeTime (time) {
            return encodeDate(time);
        },
        _downloadFile (record) {
            let fileName = `${record.originFileName}`;
            downloadFile(`${AIHUB_URL.download}/${record.id}`, 'get', fileName);
        }
    }


};
</script>

<style lang="less">
.algorithm-manager__container{
    height: 100%;
    display: flex;
    background: #fff;
    .algorithm-manager__title{
        font-size: 18px;
        color: #FFFFFF;
        font-weight: bold;
        margin: 12px 24px;
    }
}
.algorithm-market__wrap{
    display: flex;
    height: calc(100% - 48px);
    width: 100%;
}
.market-nav__left {
    padding: 0 8px;
    margin-left: 8px;
    border-right: 1px solid #ddd;
    padding-top: 20px;
    border-top: 1px solid #ddd;
}
.market-nav__title {
    padding-top: 3px;
    font-size: 14px;
    color: #999;
    margin-bottom: 10px;
    padding-left: 8px;
}
.market-nav__item {
    font-size: 14px;
    color: #14161a;
    width: 144px;
    text-indent: 8px;
    cursor: pointer;
    line-height: 36px;
    &.active,&:hover{
        color: #204ed9;
        background: #e8f0ff;
    }
}
.switch-card-container {
    height: 100%;
    width: 100%;
    .page-title{
        margin: 0;
        padding: 0 12px;
        border: none;
    }
    .switch-card-container__content{
        height: 100%;
        .card-container{
            height: 100%;
            background: #fff;
            width: calc(100% - 169px);
             flex: 1;
            .sfv-grid{
                border: none;
                display: flex;
                flex-direction: column;
                .sfv-toolbar{
                    border-top: 1px solid #DEE3ED;
                    border-bottom: 1px solid #DEE3ED;
                    width: auto;
                }

            }
        }
    }
    .algorithm-list__total{
        overflow: auto;
        height: calc(100% - 88px);
        .sfv-pagination__wrapper{
            border:none;
        }
        .algorithm-list__item{
            border-bottom: 1px solid #DEE3ED;
            height: 150px;
            color: #A3A3A3;
            display: flex;
            flex-direction: column;
            padding-left: 20px;
            // &:last-child{
            //     border-bottom:none;
            // }
            .algorithm-item__top{
                display:flex;
                justify-content: space-between;
                margin-bottom: 22px;
                margin-top: 22px;
                .algorithm-title{
                    font-size: 16px;
                    color: #1F1F1F;
                    font-weight: 700;
                    margin-right:20px;
                    margin-left: -8px;
                }
                .algorithm-time{
                    display:flex;
                    img{
                        width: 16px;
                        height: 16px;
                        margin-right: 4px;
                    }
                }
                .left{
                    display:flex;
                    align-items:center;
                }
            }
            .algorithm-item__center{
                margin-bottom: 16px;
                display: flex;
                height:24px;
            }
            .algorithm-item__bottom{
                display: flex;
                .description{
                    display: inline-block;
                    width: 94%;
                }
            }
        }
    }

}
</style>
